<template>
  <a-modal v-model:visible="visible" :title="modalTitle" width="35%" @ok="handleSubmit" @cancel="close">
    <a-form :model="formState" :label-col="{ span: 4 }" ref="formRef">
      <a-form-item label="团长名称" name="name"
        :rules="[{ required: formState.is_tuan == 0 ? true : false, message: '请输入团长名称' }]">
        <a-input v-model:value="formState.name" placeholder="请输入团长名称" />
      </a-form-item>
      <a-form-item label="一级分销比例" name="one_rebate">
        <a-input-number style="width: 260px" v-model:value="formState.one_rebate" placeholder="请输入一级分销比例"
          addon-after="%" />
      </a-form-item>
      <a-form-item label="二级分销比例" name="two_rebate">
        <a-input-number style="width: 260px" v-model:value="formState.two_rebate" placeholder="请输入二级分销比例"
          addon-after="%" />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-switch v-model:checked="formState.status" checked-children="开启" un-checked-children="关闭" :checkedValue="1"
          :unCheckedValue="0" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import useModal from "@/utils/useModal";
import { reactive, ref } from "vue";
import { setTuan, info } from "@/api/user";
import { message } from "ant-design-vue";

const emits = defineEmits(["modal-success"]);
const { visible, modalTitle } = useModal();
const formRef = ref();
const formState = reactive({
  id: null,
  name: "",
  one_rebate: "",
  two_rebate: "",
  status: null
});
const show = (model) => {
  visible.value = true;
  modalTitle.value = "设置团长";
  //获取详情
  getDetails(model.user_id);
};
// 获取详情
const getDetails = (id) => {
  info({
    id: id,
  }).then((res) => {
    if (res.code === 0) {
      const data = res.data;
      resetForm({
        user_id: data.user_id,
        ...data?.userTuan
      });
    }
  });
};
// 赋值
const resetForm = function (values) {
  for (var i in values) {
    formState[i] = values[i];
  }
};
// 关闭
const hide = () => {
  visible.value = false;
  formRef.value.resetFields();
};
const close = () => {
  formRef.value.resetFields();
};
// 保存
const handleSubmit = async () => {
  const params = {
    id: formState.user_id,
    name: formState.name,
    one_rebate: formState.one_rebate,
    two_rebate: formState.two_rebate,
    status: formState.status
  };
  await formRef.value.validate().then(() => {
    setTuan(params).then((res) => {
      if (res.code == 0) {
        message.success(res.msg);
        emits("modal-success");
        hide();
      }
    });
  });
};

// 暴露方法
defineExpose({ show });
</script>
